package plus.ldl.ldltest.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import plus.ldl.ldltest.pojo.Log;
import plus.ldl.ldltest.service.LogService;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author ldl.plus
 * @date 2020年04月29日  16:29
 * 自定义切面
 */
@Component
@Aspect
public class CustomAspect {

    private static final Logger logger = LoggerFactory.getLogger(CustomAspect.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LogService logService;

    @Pointcut("execution(* plus.ldl.ldltest.controller.*.*(..))")
    private void pointcut() {
    }

    @Before("pointcut()")
    public void before() {
        System.out.println("CustomAspect.before");
        // String path = request.getServletPath();
        // System.out.println("path = " + path);
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) {
        long start = System.currentTimeMillis();
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable throwable) {
            logger.error(pjp.getTarget().getClass().getName() + "类的" + pjp.getSignature().getName() + "方法错误：" + throwable.getMessage());
        }
        long end = System.currentTimeMillis();
        logger.info(pjp.getTarget().getClass().getName() + "类的" + pjp.getSignature().getName() + "方法消耗的时间：" + (end - start));

        Log log = new Log();
        log.setInterviewTime(LocalDateTime.now().toString());
        log.setTimeConsuming(end - start);
        log.setMethodName(pjp.getSignature().getName());
        log.setRequestURI(request.getRequestURI());

        logService.controllerLog(log);
        return proceed;
    }
}
